package com.openspring.framework.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.web.multipart.MultipartFile;

public class FileUpload {

	/**
	 * 上传文件写入指定dir,并且返回文件路径
	 * @param file
	 * @param dir
	 * @return
	 */
	public static String writeImage(MultipartFile file, String dir, String path) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String fileName = dateFormat.format(new Date()) + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
		FileOutputStream fs = null;
		try {
			File fir = new File(dir);
			if(!fir.isDirectory()) {
				fir.mkdirs();
			}
			fs = new FileOutputStream(dir + fileName);
	        byte[] buffer = file.getBytes();
            fs.write(buffer);
            fs.flush();
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			try {
				if(fs != null) {
					fs.close();
				}
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
		return path + fileName;
	}
	
	/**
	 * 上传文件写入指定dir,并且返回文件路径
	 * @param file
	 * @return
	 */
	public static String writeImage(MultipartFile file) {
		Resource res = new ClassPathResource("fileupload.properties");
		Properties pro = new Properties();
		try {
			pro.load(res.getInputStream());
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		return writeImage(file, pro.getProperty("file.images"), pro.getProperty("file.images.path"));
	}
	
	public static void deleteImage(String name) {
		Resource res = new ClassPathResource("fileupload.properties");
		Properties pro = new Properties();
		try {
			pro.load(res.getInputStream());
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		Resource resx = new FileSystemResource(pro.getProperty("file.images") + name);
		try {
			resx.getFile().delete();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
}
